package com.LeeCode;

/**
 * 无限数组的最短子数组
 */

public class Code2875 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        int target = 6;
        System.out.println(new Code2875().minSizeSubarray(nums, target));
    }

    public int minSizeSubarray(int[] nums, int target) {
        int len = nums.length;
        long totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }
        if (totalSum == target) {
            return len;
        }

        int cnt = 0;
        while (target > totalSum) {
            cnt++;
            target -= totalSum;
        }

        int ans = Integer.MAX_VALUE, left = 0;
        totalSum = 0;
        for (int right = 0; right < 2 * len; right++) {
            totalSum += nums[right % len];
            while (totalSum > target) {
                totalSum -= nums[left % len];
                left++;
            }
            if (target == totalSum) {
                ans = Math.min(ans, right - left + 1);
            }
        }
        return ans == Integer.MAX_VALUE ? -1 : ans + cnt * len;
    }
}
